package com.lanhao.aot.carrierintegration.JT;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Maps;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

/**
 * 极兔API对接
 * 
 * @author KunZhou
 */
public class JiTuAPIUtil {
	private static final Logger LOG = LoggerFactory.getLogger(JiTuAPIUtil.class);
//	public static final String CREATE_ORDER_URL = "https://demoopenapi.jtjms-sa.com/webopenplatformapi/api/order/addOrder?uuid=fcc955d3a9284492961b7b75c221af85";
//	public static final String PRINT_ORDER_FILE = "https://demoopenapi.jtjms-sa.com/webopenplatformapi/api/order/printOrder?uuid=fcc955d3a9284492961b7b75c221af85";
//	public static final String PRINT_ORDER_URL = "https://demoopenapi.jtjms-sa.com/webopenplatformapi/api/order/printOrderUrl?uuid=fcc955d3a9284492961b7b75c221af85";
//	public static final String PRINT_ORDER_JSON = "https://demoopenapi.jtjms-sa.com/webopenplatformapi/api/order/printOrderJson?uuid=fcc955d3a9284492961b7b75c221af85";
//	// Test Env Param
//	public static final String apiAccount = "292508153084379141"; // api账号
//	public static final String privateKey = "a0a1047cce70493c9d5d29704f05d0d9"; // 平台密钥
//	public static final String customerCode = "J0086024173"; // 协议客户账号
//	public static final String orderPassword = "Aa123456"; // 协议客户密码
	
	public static final String CREATE_ORDER_URL = "https://openapi.jtjms-sa.com/webopenplatformapi/api/order/addOrder";
	public static final String PRINT_ORDER_FILE = "https://openapi.jtjms-sa.com/webopenplatformapi/api/order/printOrder";
	public static final String PRINT_ORDER_URL = "https://openapi.jtjms-sa.com/webopenplatformapi/api/order/printOrderUrl";
	public static final String PRINT_ORDER_JSON = "https://openapi.jtjms-sa.com/webopenplatformapi/api/order/printOrderJson";
	// Prod Env Param -- KSA
	public static final String apiAccount = "553956276275511330"; // api账号
	public static final String privateKey = "b9823754da314ee2a0ba3314a0af2ae6"; // 平台密钥
	public static final String CustomerCode_SA = "J0086003640"; // KSA协议客户账号
	public static final String OrderPassword_SA = "N83npZj6"; // KSA协议客户密码
	
	public static final String CustomerCode_UAE = "J0086003703"; // UAE协议客户账号
	public static final String OrderPassword_UAE = "YmO6E512"; // UAE协议客户密码
	
	private static final String SLAT = "jadada236t2";

	public static void main(String[] args) {
//		createOrder("UAE");
		
		try {
			printOrder("JTE300083066505", "UAE");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	 // r={"code":"1","msg":"success","data":"https://uat-jmssa-file.s3.me-south-1.amazonaws.com/yl-web-jmssa-openplatform-api/jmssa_openplatform_order_pdf/20230803/UTE010005912696.pdf?response-content-disposition=inline%3B%20filename%3DUTE010005912696.pdf&response-content-encoding=UTF-8&response-content-type=application%2Fpdf&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20230803T173808Z&X-Amz-SignedHeaders=host&X-Amz-Expires=604800&X-Amz-Credential=AKIAY3KSSVR4WGN3FJGS%2F20230803%2Fme-south-1%2Fs3%2Faws4_request&X-Amz-Signature=ca7713d61dbc8d81fdfb66c2be3db7eb64e796a8d45087a6445418405ecda369"}
	
	// UTE010005912615
	// UTE010005912378
	// UTE010005912055
	// UTE010005912696

	private static void printOrder(String billCode, String countryCode) throws IOException {
		JSONObject req = new JSONObject();
		req.put("billCode", billCode); // 运单号
		String bizContent = "";
		if("KSA".equals(countryCode)) {
			bizContent = processSABizContent(req);
		} else if("UAE".equals(countryCode)) {
			bizContent = processUAEBizContent(req);
		}
		Map<String, String> headers = getHeaderMap(bizContent);
		HttpResponse execute = HttpRequest.post(PRINT_ORDER_URL).addHeaders(headers).form("bizContent", bizContent).execute();
		// {Transfer-Encoding=[chunked], null=[HTTP/1.1 200], X-Cache=[Miss from cloudfront], Server=[nginx], Access-Control-Allow-Methods=[GET,PUT,DELETE, POST, OPTIONS], X-Amz-Cf-Pop=[FRA56-P5], Connection=[keep-alive], Date=[Thu, 03 Aug 2023 15:00:08 GMT], Via=[1.1 fc562aab29280948aa0691960bee3d6a.cloudfront.net (CloudFront)], X-Frame-Options=[SAMEORIGIN], Content-Security-Policy=[upgrade-insecure-requests;connect-src *], Content-Encoding=[gzip], X-Amz-Cf-Id=[seG38khVZr9gLHLO0ZqoK1SOZH_bWVPOQBpiOJaj8EHGMjV4CX8BwQ==], Vary=[Accept-Encoding], X-XSS-Protection=[1; mode=block], Content-Type=[application/json;charset=UTF-8]}
		String contentType = execute.header("Content-Type");
		LOG.info("contentType={}", contentType);
		if ("application/pdf".equals(contentType)) {
			File file = new File("D:/" + billCode + ".pdf");
			execute.writeBody(file);
			LOG.info("调用极兔打印订单API, 获取标签成功, 返回标签保存路径 path={}", file.getAbsoluteFile());
		} else {
			String respBody = execute.body();
			LOG.info("调用极兔打印订单API, 请求地址url={}, 请求头参数header={}， 请求体参数bizContent={}, 返回结果 r={}", PRINT_ORDER_JSON,
					JSON.toJSONString(headers), bizContent, respBody);
			JSONObject result = JSON.parseObject(respBody);
			int code = result.getIntValue("code");
			String msg = result.getString("msg");
			if (code == 1) {
				String data = result.getString("data");
				LOG.info("调用极兔打印面单订单API返回成功，运单地址url={}", data);
				HttpUtil.downloadFile(data, new File("D:/" + billCode + ".pdf"));
			} else {
				LOG.info("调用极兔打印订单API返回失败了，code={}, msg={}", code, msg);
			}
		}
	}
	
	
	private static String processSABizContent(JSONObject req) {
		req.put("digest", digestForBizParam(CustomerCode_SA, OrderPassword_SA, privateKey));
        req.put("customerCode", CustomerCode_SA);
        return req.toJSONString();
	}
	
	private static String processUAEBizContent(JSONObject req) {
		req.put("digest", digestForBizParam(CustomerCode_UAE, OrderPassword_UAE, privateKey));
        req.put("customerCode", CustomerCode_UAE);
        return req.toJSONString();
	}
	
	private static Map<String, String> getHeaderMap(String bizContent) {
		Map<String, String> headers = Maps.newHashMap();
		headers.put("digest", digestForHead(bizContent, privateKey));
		headers.put("timestamp", System.currentTimeMillis() + "");
		headers.put("apiAccount", apiAccount);
		return headers;
	}

	public static void createOrder(String countryCode) {

		JSONObject req = new JSONObject();

		JSONObject sender = new JSONObject();
		JSONObject receiver = new JSONObject();
		req.put("txlogisticId", "10000000001293"); // 客户订单号（传客户自己系统的订单号）
		/**
		 * 快件类型：仅支持 
		 * EZ：standard（UAE)；
		 * EZKSA：standard（KSA)； 
		 * Reverse: Reverse（KSA）；
		 * ReverseUAE: Reverse（UAE） 
		 * SDD:Same Day（KSA） 
		 * SDDUAE:Same Day（UAE） SCH:
		 * SCHEDULE（KSA） 
		 * SCHUAE: SCHEDULE（UAE）
		 */
		String expressType = "";
		if("KSA".equals(countryCode)) {
			expressType = "Reverse";
		} else if("UAE".equals(countryCode)) {
			expressType = "ReverseUAE";
		}
		req.put("expressType", expressType); // 快件类型 标准快递EZ
		req.put("orderType", "1"); // 订单类型（有客户编号为月结）1、 散客；2、月结；
		req.put("serviceType", "01"); // 服务类型 ：02 门店寄件 ； 01 上门取件
		req.put("deliveryType", "03"); // 派送类型： 06 代收点自提 05 快递柜自提 04 站点自提 03 派送上门
		req.put("goodsType", "ITN1");
		req.put("operateType", "1"); // 1 新增 2 修改
		req.put("weight", "0.25");
		if("KSA".equals(countryCode)) {
			// 发件人
			sender.put("name", "TestSASender");
			sender.put("mobile", "+966560287084");
			sender.put("phone", "");
			sender.put("countryCode", countryCode);
			sender.put("prov", "Al Qassim");
			sender.put("city", "Al Ammarah");
			// sender.put("area","沂源县");
			sender.put("address", "cdscds 132132131cdscd cdsc");
			req.put("sender", sender);
			
			// 收件人
			receiver.put("name", "TestSAReceiver");
			receiver.put("mobile", "+966560287085");
			receiver.put("phone", "");
			receiver.put("countryCode", countryCode);
			receiver.put("prov", "Al Jawf");
			receiver.put("city", "Abu Ajram");
			// receiver.put("area","沂源县");
			receiver.put("address", "sdfsacdscdscds2a");
			req.put("receiver", receiver);
		} else if("UAE".equals(countryCode)) {
			// 发件人
			sender.put("name", "TestUAESender");
			sender.put("mobile", "00971-529767656");
			sender.put("phone", "");
			sender.put("countryCode", countryCode);
			sender.put("prov", "UMM AL QUWAIN");
			sender.put("city", "UMM AL QUWAIN");
			// sender.put("area","沂源县");
			sender.put("address", "WAREHOUSE NO.26D,INJAZ ZONE COMPLEX,NEW INDUSTRIALS AREA");
			req.put("sender", sender);
			
			// 收件人
			receiver.put("name", "TestUAEReceiver");
			receiver.put("mobile", "00971-529767656");
			receiver.put("phone", "");
			receiver.put("countryCode", countryCode);
			receiver.put("prov", "UMM AL QUWAIN");
			receiver.put("city", "UMM AL QUWAIN");
			// receiver.put("area","沂源县");
			receiver.put("address", "WAREHOUSE NO.36D,INJAZ ZONE COMPLEX,NEW INDUSTRIALS AREA");
			req.put("receiver", receiver);
		}

		JSONArray items = new JSONArray();
		JSONObject item = new JSONObject();
//        item.put("number","1");
//        item.put("itemType","ITN1");
		item.put("itemName", "AnHe Goods");
//        item.put("priceCurrency","DHS");
		item.put("itemValue", "0.01");
//        item.put("itemUrl","");
//		item.put("desc", "AnHe Goods");

		items.add(item);

		req.put("items", items);
		String bizContent = "";
		if("KSA".equals(countryCode)) {
			bizContent = processSABizContent(req);
		} else if("UAE".equals(countryCode)) {
			bizContent = processUAEBizContent(req);
		}
		Map<String, String> headers = getHeaderMap(bizContent);

		String respBody = HttpRequest.post(CREATE_ORDER_URL).addHeaders(headers).form("bizContent", bizContent)
				.execute().body();

		LOG.info("调用极兔创建订单API, 请求地址url={}，请求头参数header={}， 请求体参数bizContent={}, 返回结果 r={}", CREATE_ORDER_URL,
				JSON.toJSONString(headers), bizContent, respBody);
		JSONObject result = JSON.parseObject(respBody);
		int code = result.getIntValue("code");
		String msg = result.getString("msg");
		if (code == 1) {
			JSONObject dataObject = result.getJSONObject("data");
			String billCode = dataObject.getString("billCode");
			String sortingCode = dataObject.getString("sortingCode");
			LOG.info("调用极兔创建订单API返回成功，运单号billCode={}， 三段码sortingCode={}", billCode, sortingCode);
		} else {
			LOG.info("调用极兔创建订单API返回失败了，code={}， msg={}", code, msg);
		}
	}

	public static String digestForHead(String json, String privateKey) {
		String signStr = json + privateKey;
		byte[] encode = (new Base64()).encode(DigestUtils.md5(signStr));
		return new String(encode);
	}

	public static String digestForBizParam(String customerCode, String customerPwd, String privateKey) {
		String pwd = DigestUtils.md5Hex(customerPwd + SLAT).toUpperCase();
		byte[] encode = (new Base64()).encode(DigestUtils.md5(customerCode + pwd + privateKey));
		return new String(encode);
	}
}
